<template>
    <view class="vote-from">
        <view v-if="!voteOptionMap || Object.keys(voteOptionMap).length === 0" class="no-data">
            暂无投票选项
        </view>
        <view class="vote-from-content" v-for="(options, questionTitle) in voteOptionMap" :key="questionTitle">
            <view class="vote-from-content-title">
                {{ questionTitle }} 
            </view>
            <view class="vote-from-content-item">
                <VoteFromItem
                    :optionId="item.optionId"
                    :isVotingInfo="isVotingInfo"    
                    :voteNum="item.voteNum"
                    :areaNum="item.areaNum"
                    v-for="(item, idx) in options"
                     :key="item.optionId"
                    :checked="isOptionSelected(item.optionId)"
                    :label="item.name"
                    :optionInfo="getQuestionOptionInfo(questionTitle)"
                    @change="handleSelect(idx, questionTitle)"
                />
            </view>
        </view>
    </view>
</template>

<script>
import VoteFromItem from './VoteFromItem.vue'
export default {
    props:{
        voteOptions:{
            deep:true,
            type:Array,
            default:()=>[]
        },
        voteOptionMap:{
            deep:true,
            type:Object,
            default:()=>{}
        },
        optionInfo:{
            deep:true,
            type:Object,
            default:()=>{}
        },
               
        isVotingInfo:{
            immediate:true,
            deep:true,
            type:Object,
            default:()=>{}
        }
    },
    watch:{
        isVotingInfo:{
            handler(newVal){
           
               this.initSelectedOptions()
            },
            deep:true,
            immediate:true
        },
        optionInfo:{
            handler(newVal){
           
            },
            deep:true,
            immediate:true
        },
        voteOptionMap:{
            handler(newVal){
          
            },
            deep:true,
            immediate:true
        }
    },
    components:{
        VoteFromItem
    },
    name: 'VoteFrom',
    data(){
        return {
            selectedOptionIds: [], // 存储选中的选项ID
            selectedOptionsByQuestion: {} // 按问题存储选中的选项
        }
    },
    mounted() {
        // 初始化时处理已投票状态
        this.initSelectedOptions()
    },
    methods: {
        clear(){
            this.selectedOptionIds = []
        },
        // 检查选项是否被选中
        isOptionSelected(optionId) {
            return this.selectedOptionIds.includes(String(optionId))
        },
        // 获取每个问题的选项信息（包含该问题的总投票数）
        getQuestionOptionInfo(questionTitle) {
            const options = this.voteOptionMap[questionTitle] || []
            const questionTotalVoteNum = options.reduce((total, item) => total + Number(item.voteNum), 0)
            const questionTotalAreaNum = options.reduce((total, item) => total + Number(item.areaNum), 0)
            
            return {
                zongvoteNum: questionTotalVoteNum,
                zongvoteSize: questionTotalAreaNum,
                voteRule: this.optionInfo.voteRule
            }
        },
        // 初始化选中状态
        initSelectedOptions() {
            // 初始化按问题存储的选中状态
            this.selectedOptionsByQuestion = {}
            if (this.voteOptionMap) {
                Object.keys(this.voteOptionMap).forEach(questionTitle => {
                    this.$set(this.selectedOptionsByQuestion, questionTitle, [])
                })
            }
            
            if (this.isVotingInfo.isVoting && this.isVotingInfo.optionId) {
                // 处理已投票状态
                let optionIds = this.isVotingInfo.optionId
                if (Array.isArray(optionIds)) {
                    // 如果是数组，转换为字符串数组
                    this.selectedOptionIds = optionIds.map(id => String(id))
                } else {
                    // 如果是单个值，转换为数组
                    this.selectedOptionIds = [String(optionIds)]
                }
                
                // 将选中的选项ID按问题分类
                this.selectedOptionIds.forEach(optionId => {
                    Object.keys(this.voteOptionMap).forEach(questionTitle => {
                        const options = this.voteOptionMap[questionTitle] || []
                        const option = options.find(item => String(item.optionId) === optionId)
                        if (option) {
                            if (!this.selectedOptionsByQuestion[questionTitle]) {
                                this.$set(this.selectedOptionsByQuestion, questionTitle, [])
                            }
                            this.selectedOptionsByQuestion[questionTitle].push(optionId)
                        }
                    })
                })
                
              
            } else {
                this.selectedOptionIds = []
            }
        },
        getSelectedIndex(){
            // 返回选中的选项对象数组
            let selectedOptions = []
            Object.keys(this.voteOptionMap).forEach(questionTitle => {
                const options = this.voteOptionMap[questionTitle] || []
                const selectedOption = options.find(item => this.selectedOptionIds.includes(String(item.optionId)))
                if (selectedOption) {
                    selectedOptions.push(selectedOption)
                }
            })
            return selectedOptions
        },
        handleSelect(idx, questionTitle) {
            // 只有在投票进行中且未投票的情况下才允许选择
            if(this.isVotingInfo.status == 1 && !this.isVotingInfo.isVoting){
                const options = this.voteOptionMap[questionTitle] || []
                const selectedOption = options[idx]
                
                if (selectedOption) {
                    // 单选逻辑：只清空当前问题的选择，不影响其他问题
                    this.$set(this.selectedOptionsByQuestion, questionTitle, [String(selectedOption.optionId)])
                    
                    // 更新全局选中选项ID数组
                    this.updateSelectedOptionIds()
                    
                    // 传递选中的选项
                    const selectedItems = this.getSelectedIndex()
                 
                    this.$emit("input", selectedItems)
                }
            }
        },
        // 更新全局选中选项ID数组
        updateSelectedOptionIds() {
            this.selectedOptionIds = []
            Object.keys(this.selectedOptionsByQuestion).forEach(questionTitle => {
                const questionSelectedIds = this.selectedOptionsByQuestion[questionTitle] || []
                this.selectedOptionIds = this.selectedOptionIds.concat(questionSelectedIds)
            })
        }
    }
}
</script>

<style lang="scss" scoped>
.vote-from{
    width: 100%;
    height: 100%;
    background: #fff;
    border-radius: 18rpx;
    padding:30rpx 20rpx ;
    margin: 0 4rpx;
    box-shadow: 0rpx 0rpx 27rpx 0rpx rgba(0,0,0,0.03), 0rpx -14rpx 16rpx 0rpx rgba(20,77,169,0.09);
    border-radius: 16rpx ;
    display: flex;
    flex-direction: column;
    justify-content:center;
    align-items: center;
        &-content{
           width: 100%;
           margin-bottom: 30rpx;
           &:last-child {
               margin-bottom: 0;
           }
           &-title{
            font-weight: 600;
            font-size: 30rpx;
            color: #000000;
            margin-bottom: 20rpx;
            padding: 10rpx 0;
            border-bottom: 1rpx solid #f0f0f0;
           }
           &-item{
            width: 100%;
            margin-top: 20rpx;
         
           }
        }
        .no-data {
            text-align: center;
            color: #999;
            padding: 40rpx;
        }
    
}
</style>
